<template>
  <div class="course-page">
    <!-- 顶部标题区域 -->
    <div class="page-header mb-6">
      <h2 class="title">课程管理</h2>
      <p class="desc">管理焊接相关课程，包括课程内容和测验设置</p>
    </div>

    <!-- 搜索与操作区 -->
    <el-card class="search-card mb-6">
      <div class="search-container">
        <el-row :gutter="24">
          <!-- 搜索与筛选 -->
          <el-col :span="24">
            <el-row :gutter="24">
              <el-col :span="10">
                <el-input
                  v-model="searchForm.keyword"
                  placeholder="搜索课程名称"
                  prefix-icon="el-icon-search"
                  clearable
                  @keyup.enter.native="handleSearch"
                ></el-input>
              </el-col>
              <el-col :span="3" style="min-width: 160px;">
                <el-select
                  v-model="searchForm.category"
                  placeholder="所有分类"
                  clearable
                  filterable
                >
                  <el-option 
                    v-for="item in categoryList" 
                    :key="`categoryList_${item.id}`" 
                    :label="item.name" 
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-col>
              <el-col :span="3" style="min-width: 160px;">
                <el-select
                  v-model="searchForm.status"
                  placeholder="所有状态"
                  clearable
                >
                  <el-option label="启用" value="1"></el-option>
                  <el-option label="停用" value="0"></el-option>
                </el-select>
              </el-col>
              <el-col :span="4" style="min-width: 200px;">
                <el-button 
                  type="primary"
                  icon="el-icon-search"
                  @click="handleSearch"
                >
                  搜索
                </el-button>
                <el-button 
                  @click="handleReset"
                >
                  重置
                </el-button>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 课程列表 -->
    <el-card>
      <div slot="header" style="display: flex;" class="clearfix">
        <el-button type="primary" icon="el-icon-plus" @click="openCourseModal()" size="medium">
          新增课程
        </el-button>
      </div>
      <el-table
        :data="courseList"
        v-loading="loading"
        border
        stripe
        :header-cell-style="{ background: '#f5f7fa' }"
        @row-click="handleRowClick"
      >
        <!-- 序号列 -->
        <el-table-column
          prop="id"
          label="ID"
          width="80"
          align="center"
        ></el-table-column>

        <!-- 课程名称列 -->
        <el-table-column
          prop="name"
          label="课程名称"
          min-width="200"
        ></el-table-column>

        <!-- 课程分类列 -->
        <el-table-column
          label="课程分类"
          min-width="120"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag
              size="small"
              :type="getTypeTagType(scope.row.type)"
            >
              {{ scope.row.category?.name || getTypeText(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 内容数量列 -->
        <el-table-column
          label="内容数量"
          min-width="140"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.contentCount }}个知识点
          </template>
        </el-table-column>

        <!-- 测验数量列 -->
        <el-table-column
          label="测验数量"
          min-width="140"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.quizCount }}次测验
          </template>
        </el-table-column>

        <!-- 绑定学生数量列 -->
        <el-table-column
          label="绑定学生"
          min-width="120"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="openStudentListModal(scope.row, $event)"
            >
              {{ scope.row.studentCount || 0 }}人
            </el-button>
          </template>
        </el-table-column>

        <!-- 状态列 -->
        <el-table-column
          label="状态"
          min-width="120"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag
              size="small"
              :class="['course-status-tag', `course-status-${scope.row.status}`]"
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column
          label="操作"
          min-width="200"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="openViewModal(scope.row, $event)"
            >
              查看
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="openCourseModal(scope.row, $event)"
            >
              编辑
            </el-button>
            <el-button
              type="text"
              size="small"
              :style="{ color: scope.row.status === 1 ? '#F53F3F' : '#00B42A' }"
              @click="handleStatusToggle(scope.row, $event)"
            >
              {{ scope.row.status === 1 ? '停用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.page"
          :page-sizes="[10, 20, 50]"
          :page-size="pagination.size"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑课程抽屉 -->
    <el-drawer
      :title="modalTitle"
      :visible.sync="courseModalVisible"
      direction="rtl"
      size="60%"
      :close-on-click-modal="false"
      class="course-drawer"
    >
      <div style="padding: 0 20px 20px;" v-loading="courseDetailLoading" element-loading-text="加载课程详情中...">
        <el-form
          ref="courseForm"
          :model="formData"
          :rules="formRules"
          label-width="120px"
          class="drawer-form"
        >
          <!-- 基础信息区域 -->
          <el-form-item label="课程名称" prop="name" class="form-item">
            <el-input 
              v-model="formData.name" 
              placeholder="请输入课程名称"
              class="full-width"
            ></el-input>
          </el-form-item>

          <el-row :gutter="20" class="form-item" style="margin-top: 20px;">
            <el-col :span="8">
              <el-form-item label="课程分类" prop="category">
                <el-select 
                  v-model="formData.category" 
                  placeholder="请选择或输入课程分类"
                  filterable
                  allow-create
                  default-first-option
                >
                  <el-option 
                    v-for="(item, index) in categoryOptions" 
                    :key="index" 
                    :label="item" 
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="课程状态" prop="status">
                <el-select 
                  v-model="formData.status" 
                  placeholder="请选择课程状态"
                >
                  <el-option label="启用" value="active"></el-option>
                  <el-option label="停用" value="disabled"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- <el-form-item label="课程描述" class="form-item">
            <el-input 
              v-model="formData.description" 
              type="textarea" 
              rows="3"
              placeholder="请输入课程描述（选填）"
              class="full-width"
            ></el-input>
          </el-form-item> -->

          <!-- 课程内容区域 -->
          <div style="padding:20px;">
            <div class="content-header">
              <h4 class="content-title">课程内容</h4>
            </div>

            <!-- 知识学习部分 -->
            <div class="learning-section mb-6">
              <div class="section-header">
                <i class="el-icon-book section-icon"></i>
                <h5 class="section-title">知识学习</h5>
                <p class="section-desc">(学生需要学习的理论知识和文档)</p>
              </div>

              <div class="section-content">
                <div class="content-operation">
                  <span class="content-label">学习内容列表</span>
                  <div class="content-buttons">
                    <el-button
                      type="text"
                      size="mini"
                      @click="addLearningContent()"
                    >
                      <i class="el-icon-plus"></i> 添加学习内容
                    </el-button>
                  </div>
                </div>

                <div class="content-list">
                  <el-table
                    :data="formData.learningContents"
                    border
                    size="mini"
                    :show-header="false"
                    class="learning-table"
                  >
                    <el-table-column width="40" align="center">
                      <template slot-scope="scope">
                        {{ scope.$index + 1 }}
                      </template>
                    </el-table-column>
                    <el-table-column width="160">
                      <template slot-scope="scope">
                        <el-select
                          v-model="scope.row.type"
                          size="mini"
                          @change="changeContent_type(scope.$index)"
                        >
                          <el-option label="理论知识" value="theory"></el-option>
                          <el-option label="WPS文档" value="wps"></el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column>
                      <template slot-scope="scope">
                        <el-select
                          v-model="scope.row.contentId"
                          size="mini"
                          placeholder="请选择内容"
                          class="content-select"
                        >
                          <el-option
                            v-for="item in getContentOptions(scope.row.type)"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                          ></el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column width="40" align="center">
                      <template slot-scope="scope">
                        <el-button
                          type="text"
                          size="mini"
                          @click="deleteLearningContent(scope.$index)"
                          style="color: #86909C"
                        >
                          <i class="el-icon-delete"></i>
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </div>

            <!-- 测验与考试部分 -->
            <div class="quiz-section mb-6" style="margin-top: 20px;">
              <div class="section-header">
                <i class="el-icon-edit-outline section-icon"></i>
                <h5 class="section-title">测验与考试</h5>
                <p class="section-desc">(课程测验和考试设置)</p>
              </div>

              <div class="section-content">
                <div class="content-operation">
                  <span class="content-label">测验与考试设置</span>
                  <el-button
                    type="text"
                    size="mini"
                    @click="addTest"
                  >
                    <i class="el-icon-plus"></i> 添加测验/考试
                  </el-button>
                </div>

                <div class="quiz-list">
                  <div
                    v-for="(test, testIndex) in formData.tests"
                    :key="test._uid || testIndex"
                    class="quiz-item"
                  >
                    <div class="quiz-header">
                      <span class="quiz-title">
                        <el-tag :type="test.testType === 'quiz' ? 'success' : 'warning'" size="mini">
                          {{ test.testType === 'quiz' ? '随堂测验' : '考试' }}
                        </el-tag>
                        {{ testIndex + 1 }}
                      </span>
                      <el-button
                        type="text"
                        size="mini"
                        @click="deleteTest(testIndex)"
                        style="color: #86909C"
                      >
                        <i class="el-icon-delete"></i> 删除
                      </el-button>
                    </div>

                    <el-row :gutter="20" class="quiz-form">
                      <el-col :span="8">
                        <el-form-item label="类型" label-width="80px">
                          <el-select
                            v-model="test.testType"
                            placeholder="请选择类型"
                            style="width: 100%;"
                            :disabled="!!test.paperId"
                          >
                            <el-option label="随堂测验" value="quiz"></el-option>
                            <el-option label="考试" value="exam"></el-option>
                          </el-select>
                          <div v-if="test.paperId" style="font-size: 12px; color: #909399; margin-top: 4px;">
                            <!-- 从试卷选择的类型不可修改 -->
                          </div>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item
                          label="名称"
                          label-width="80px"
                          :prop="`tests[${testIndex}].name`"
                          :rules="[
                            { required: true, message: '请输入名称', trigger: 'blur' }
                          ]"
                        >
                          <el-input
                            v-model="test.name"
                            placeholder="请输入名称"
                            :readonly="!!test.paperId"
                            :style="test.paperId ? 'cursor: not-allowed; background-color: #f5f7fa;' : ''"
                          ></el-input>
                          <div v-if="test.paperId" style="font-size: 12px; color: #909399; margin-top: 4px;">
                            <!-- 从试卷选择的名称不可修改 -->
                          </div>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="时长（分钟）" label-width="100px">
                          <el-input
                            v-model="test.time"
                            placeholder="请输入时长"
                            type="number"
                            :min="test.testType === 'quiz' ? 5 : 30"
                            :readonly="!!test.paperId"
                            :style="test.paperId ? 'cursor: not-allowed; background-color: #f5f7fa;' : ''"
                          ></el-input>
                          <div v-if="test.paperId" style="font-size: 12px; color: #909399; margin-top: 4px;">
                            <!-- 从试卷选择的时长不可修改 -->
                          </div>
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <div class="question-section">
                      <span class="question-label">选择题目</span>
                      <div class="question-buttons">
                        <!-- 暂时隐藏从题库选择功能 -->
                        <!-- <el-button
                          type="primary"
                          size="mini"
                          @click="openQuestionSelector(testIndex)"
                        >
                          <i class="el-icon-search"></i> 从题库选择
                        </el-button> -->
                        <el-button
                          type="success"
                          size="mini"
                          @click="openExamSelector(testIndex)"
                          :disabled="!!test.paperId"
                        >
                          <i class="el-icon-document"></i> 从试卷选择
                        </el-button>
                        <div v-if="test.paperId" style="font-size: 12px; color: #909399; margin-top: 4px;">
                          <!-- 已选择试卷，不能修改 -->
                        </div>
                      </div>

                      <el-table
                        v-if="test.questions && test.questions.length > 0"
                        :data="test.questions"
                        border
                        size="mini"
                        :show-header="false"
                        class="question-table"
                        max-height="160"
                      >
                        <el-table-column width="40" align="center">
                          <template slot-scope="scope">
                            {{ scope.$index + 1 }}
                          </template>
                        </el-table-column>
                        <el-table-column>
                          <template slot-scope="scope">
                            <div class="question-content">
                              {{ scope.row.content }}
                            </div>
                          </template>
                        </el-table-column>
                        <el-table-column width="80" align="center">
                          <template slot-scope="scope">
                            <el-tag size="mini">
                              {{ getQuestionTypeText(scope.row.type) }}
                            </el-tag>
                          </template>
                        </el-table-column>
                        <!-- <el-table-column width="40" align="center">
                          <template slot-scope="scope">
                            <el-button
                              type="text"
                              size="mini"
                              @click="deleteQuestion(testIndex, scope.$index)"
                              style="color: #86909C"
                            >
                              <i class="el-icon-delete"></i>
                            </el-button>
                          </template>
                        </el-table-column> -->
                      </el-table>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 实训操作参数区域 -->
            <div style="padding:20px; margin-top:20px; background:#F7F8FA; border-radius:4px;">
              <div class="content-header">
                <h4 class="content-title">
                  <i class="el-icon-setting"></i>
                  实训操作参数
                </h4>
                <p style="font-size:12px; color:#86909C; margin:5px 0 15px 0;">
                  (为实操课程设置焊接工艺参数，列表中不显示，仅在详情中展示)
                </p>
              </div>

              <!-- 难度等级 -->
              <el-row :gutter="20" style="margin-bottom:15px;">
                <el-col :span="12">
                  <el-form-item label="难度等级">
                    <el-select 
                      v-model="formData.trainingParams.difficultyLevel" 
                      placeholder="请选择难度等级"
                      clearable
                    >
                      <el-option label="初级" :value="1"></el-option>
                      <el-option label="中级" :value="2"></el-option>
                      <el-option label="高级" :value="3"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- 焊接参数/准备(1-5) -->
              <div style="margin-bottom:10px; padding:10px; background:#FFF; border-radius:4px;">
                <div style="font-weight:500; color:#1D2129; margin-bottom:15px; font-size:13px;">
                  <i class="el-icon-connection"></i> 焊接参数准备(1-5)
                </div>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="焊接接头选择" label-width="110px">
                      <el-input 
                        v-model="formData.trainingParams.weldingJoint" 
                        placeholder="如:对接接头"
                        clearable
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="位置选择" label-width="110px">
                      <el-input 
                        v-model="formData.trainingParams.weldingPosition" 
                        placeholder="如:平焊"
                        clearable
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="材质选择" label-width="110px">
                      <el-input 
                        v-model="formData.trainingParams.baseMaterial" 
                        placeholder="如:Q235低碳钢"
                        clearable
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="厚度" label-width="110px">
                      <el-input-number 
                        v-model="formData.trainingParams.thickness" 
                        placeholder="请输入厚度"
                        :min="0"
                        :precision="2"
                        :controls="false"
                        style="width: 100%"
                      ></el-input-number>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="焊接方法" label-width="110px">
                      <el-input 
                        v-model="formData.trainingParams.weldingMethod" 
                        placeholder="如:手工电弧焊"
                        clearable
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>

              <!-- 焊接参数/准备(6-9) -->
              <div style="margin-bottom:10px; padding:10px; background:#FFF; border-radius:4px;">
                <div style="font-weight:500; color:#1D2129; margin-bottom:15px; font-size:13px;">
                  <i class="el-icon-connection"></i> 焊接参数准备(6-9)
                </div>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="填充材料" label-width="110px">
                      <el-input 
                        v-model="formData.trainingParams.fillerMaterial" 
                        placeholder="如:J422焊条"
                        clearable
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="气体类型" label-width="110px">
                      <el-input 
                        v-model="formData.trainingParams.gasType" 
                        placeholder="如:CO2"
                        clearable
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="焊缝长度" label-width="110px">
                      <el-input-number 
                        v-model="formData.trainingParams.seamLength" 
                        placeholder="请输入焊缝长度"
                        :min="0"
                        :precision="2"
                        :controls="false"
                        style="width: 100%"
                      ></el-input-number>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="焊缝层数" label-width="110px">
                      <el-input-number 
                        v-model="formData.trainingParams.weldingLayers" 
                        placeholder="请输入焊缝层数"
                        :min="1"
                        :precision="0"
                        :controls="false"
                        style="width: 100%"
                      ></el-input-number>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>

              <!-- 备注 -->
              <el-form-item label="参数备注" label-width="110px" style="margin-top:15px;">
                <el-input 
                  v-model="formData.trainingParams.remarks" 
                  type="textarea"
                  rows="2"
                  placeholder="其他工艺参数说明(选填)"
                  clearable
                ></el-input>
              </el-form-item>
            </div>
          </div>
        </el-form>
      </div>
      
      <div style="padding: 20px; border-top: 1px solid #e8e8e8; background: #fff; text-align: right;">
        <el-button @click="courseModalVisible = false">取消</el-button>
        <el-button type="primary" @click="saveCourse">保存课程</el-button>
      </div>
    </el-drawer>

    <!-- 查看课程模态框 -->
    <el-dialog
      title="课程详情"
      :visible.sync="viewModalVisible"
      width="1000px"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      top="5vh"
    >
      <div class="view-course-container" v-loading="viewDetailLoading" element-loading-text="加载课程详情中...">
        <!-- 1. 课程信息 -->
        <div class="view-base-info">
          <h3 class="course-name-title">{{ currentCourse.name }}</h3>
          <div class="course-meta-info">
            <div class="meta-row">
              <!-- <div class="meta-item-detail">
                <span class="meta-label">课程编号:</span>
                <span class="meta-value">{{ currentCourse.number || '-' }}</span>
              </div> -->
              <div class="meta-item-detail">
                <span class="meta-label">课程分类:</span>
                <span class="meta-value">{{ currentCourse.category?.name || getTypeText(currentCourse.type) }}</span>
              </div>
              <div class="meta-item-detail">
                <span class="meta-label">状态:</span>
                <el-tag
                  :class="`course-status-${currentCourse.status}`"
                  size="small"
                >
                  {{ getStatusText(currentCourse.status) }}
                </el-tag>
              </div>
              <div class="meta-item-detail">
                <span class="meta-label">创建时间:</span>
                <span class="meta-value">{{ currentCourse.createTime | formatDate }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 2. 学习内容 -->
        <div class="view-section">
          <h4 class="section-title-view">
            <i class="el-icon-reading"></i>
            学习内容
          </h4>
          <div class="section-content-view">
            <el-table
              :data="currentCourse.learningContents"
              border
              size="small"
              :header-cell-style="{ background: '#f5f7fa', textAlign: 'left' }"
            >
              <el-table-column
                label="内容类型"
                width="120"
              >
                <template slot-scope="scope">
                  <el-tag size="small" :type="scope.row.type === 'theory' ? 'primary' : 'success'">
                    {{ scope.row.type === 'theory' ? '理论知识' : 'WPS文档' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column
                prop="name"
                label="内容名称"
                min-width="200"
              ></el-table-column>
            </el-table>
            <div v-if="!currentCourse.learningContents || currentCourse.learningContents.length === 0" class="empty-tip">
              暂无学习内容
            </div>
          </div>
        </div>

        <!-- 3. 测验和考试 -->
        <div class="view-section">
          <h4 class="section-title-view">
            <i class="el-icon-edit-outline"></i>
            测验和考试
          </h4>
          <div class="section-content-view">
            <div
              v-for="(test, index) in currentCourse.tests"
              :key="index"
              class="quiz-detail-card"
            >
              <div class="quiz-card-header">
                <h5 class="quiz-card-title">
                  {{ test.testType === 'exam' ? '考试' : '测验' }} {{ index + 1 }}：{{ test.name }}
                </h5>
                <span class="quiz-card-meta">
                  <i class="el-icon-time"></i> {{ test.time || 30 }}分钟
                  <i class="el-icon-document" style="margin-left: 12px;"></i> {{ test.questions ? test.questions.length : 0 }}题
                </span>
              </div>
              <el-table
                :data="test.questions"
                border
                size="small"
                :show-header="true"
                max-height="250"
                :header-cell-style="{ background: '#f5f7fa', textAlign: 'left' }"
              >
                <el-table-column
                  label="题目内容"
                  min-width="300"
                >
                  <template slot-scope="scope">
                    <div class="question-text">{{ scope.row.content }}</div>
                  </template>
                </el-table-column>
                <el-table-column
                  label="题型"
                  width="100"
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-tag size="small">
                      {{ getQuestionTypeText(scope.row.type) }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div v-if="!currentCourse.tests || currentCourse.tests.length === 0" class="empty-tip">
              暂无测验和考试
            </div>
          </div>
        </div>

        <!-- 4. 实训参数 -->
        <div class="view-section" v-if="currentCourse.trainingParams && hasTrainingParams(currentCourse.trainingParams)">
          <h4 class="section-title-view">
            <i class="el-icon-setting"></i>
            实训操作参数
          </h4>
          <div class="section-content-view">
            <el-row :gutter="20" style="margin-bottom:10px;">
              <el-col :span="8">
                <div class="param-item">
                  <span class="param-label">难度等级:</span>
                  <span class="param-value">{{ (currentCourse.trainingParams && currentCourse.trainingParams.difficultyLevel) ? getDifficultyText(currentCourse.trainingParams.difficultyLevel) : '-' }}</span>
                </div>
              </el-col>
            </el-row>
            
            <div style="margin:15px 0 10px 0; font-weight:500; color:#1D2129; font-size:13px;">
              <i class="el-icon-connection"></i> 焊接参数准备(1-5)
            </div>
            <el-row :gutter="20" style="margin-bottom:8px;">
              <el-col :span="8">
                <div class="param-item">
                  <span class="param-label">焊接接头选择:</span>
                  <span class="param-value">{{ (currentCourse.trainingParams && currentCourse.trainingParams.weldingJoint) || '-' }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="param-item">
                  <span class="param-label">位置选择:</span>
                  <span class="param-value">{{ (currentCourse.trainingParams && currentCourse.trainingParams.weldingPosition) || '-' }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="param-item">
                  <span class="param-label">材质选择:</span>
                  <span class="param-value">{{ (currentCourse.trainingParams && currentCourse.trainingParams.baseMaterial) || '-' }}</span>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="20" style="margin-bottom:8px;">
              <el-col :span="8">
                <div class="param-item">
                  <span class="param-label">厚度:</span>
                  <span class="param-value">{{ (currentCourse.trainingParams && currentCourse.trainingParams.thickness) || '-' }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="param-item">
                  <span class="param-label">焊接方法:</span>
                  <span class="param-value">{{ (currentCourse.trainingParams && currentCourse.trainingParams.weldingMethod) || '-' }}</span>
                </div>
              </el-col>
            </el-row>

            <div style="margin:15px 0 10px 0; font-weight:500; color:#1D2129; font-size:13px;">
              <i class="el-icon-connection"></i> 焊接参数准备(6-9)
            </div>
            <el-row :gutter="20" style="margin-bottom:8px;">
              <el-col :span="8">
                <div class="param-item">
                  <span class="param-label">填充材料:</span>
                  <span class="param-value">{{ (currentCourse.trainingParams && currentCourse.trainingParams.fillerMaterial) || '-' }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="param-item">
                  <span class="param-label">气体类型:</span>
                  <span class="param-value">{{ (currentCourse.trainingParams && currentCourse.trainingParams.gasType) || '-' }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="param-item">
                  <span class="param-label">焊缝长度:</span>
                  <span class="param-value">{{ (currentCourse.trainingParams && currentCourse.trainingParams.seamLength) || '-' }}</span>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="20" style="margin-bottom:8px;">
              <el-col :span="8">
                <div class="param-item">
                  <span class="param-label">焊缝层数:</span>
                  <span class="param-value">{{ (currentCourse.trainingParams && currentCourse.trainingParams.weldingLayers) || '-' }}</span>
                </div>
              </el-col>
            </el-row>

            <!-- 参数备注 -->
            <div v-if="currentCourse.trainingParams && currentCourse.trainingParams.remarks" style="margin-top:15px;">
              <div class="param-item">
                <span class="param-label">参数备注:</span>
                <span class="param-value">{{ currentCourse.trainingParams.remarks }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 5. 绑定学生列表 -->
        <div class="view-section">
          <h4 class="section-title-view">
            <i class="el-icon-user"></i>
            绑定学生列表
          </h4>
          <div class="section-content-view">
            <el-table
              :data="currentCourse.bindStudents || []"
              border
              size="small"
              :header-cell-style="{ background: '#f5f7fa', textAlign: 'left' }"
            >
              <el-table-column
                prop="id"
                label="学生ID"
                width="80"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="name"
                label="学生姓名"
                min-width="100"
              ></el-table-column>
              <el-table-column
                prop="phone"
                label="联系电话"
                min-width="120"
              ></el-table-column>
            </el-table>
            <div v-if="!currentCourse.bindStudents || currentCourse.bindStudents.length === 0" class="empty-tip">
              暂无绑定学生
            </div>
          </div>
        </div>
      </div>
      
      <div slot="footer">
        <el-button @click="viewModalVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog
      title="确认删除"
      :visible.sync="deleteVisible"
      width="400px"
      :close-on-click-modal="false"
    >
      <div class="delete-content">
        <i class="el-icon-warning-outline warning-icon"></i>
        <p class="delete-message">
          您确定要删除课程「{{ deleteCourse.name }}」吗？
        </p>
        <p class="delete-tip">
          此操作不可撤销，删除后将同时删除该课程的所有内容和测验数据。
        </p>
      </div>
      
      <div slot="footer">
        <el-button @click="deleteVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确认删除</el-button>
      </div>
    </el-dialog>

    <!-- 题目选择对话框 -->
    <el-dialog
      title="从题库选择题目"
      :visible.sync="questionSelectorVisible"
      width="900px"
      :close-on-click-modal="false"
    >
      <div class="question-selector-container">
        <div class="selector-filter mb-4"style="margin-bottom: 20px;">
          <el-radio-group v-model="questionFilterType" size="small">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button label="single">单选题</el-radio-button>
            <el-radio-button label="multiple">多选题</el-radio-button>
            <el-radio-button label="judge">判断题</el-radio-button>
          </el-radio-group>
        </div>
        <el-table
          ref="questionSelectorTable"
          :data="filteredQuestionBank"
          border
          v-loading="questionsLoading"
          element-loading-text="加载题库中..."
          @selection-change="handleQuestionSelectionChange"
          max-height="400"
        >
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column prop="id" label="题目ID" width="80" align="center"></el-table-column>
          <el-table-column label="题型" width="100" align="center">
            <template slot-scope="scope">
              <el-tag size="small" :type="scope.row.type === 'single' ? 'primary' : scope.row.type === 'multiple' ? 'success' : 'info'">
                {{ getQuestionTypeText(scope.row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="题目内容" prop="content" min-width="300"></el-table-column>
        </el-table>
      </div>
      <div slot="footer">
        <el-button @click="questionSelectorVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmQuestionSelection">
          确定选择 ({{ selectedQuestions.length }}题)
        </el-button>
      </div>
    </el-dialog>

    <!-- 试卷选择对话框 -->
    <el-dialog
      title="从试卷列表选择"
      :visible.sync="examSelectorVisible"
      width="900px"
      :close-on-click-modal="false"
    >
      <div class="exam-selector-container">
        <!-- 搜索栏 -->
        <div class="exam-search-bar" style="margin-bottom: 16px;">
          <el-form :inline="true" size="small">
            <el-form-item label="试卷名称">
              <el-input
                v-model="examSearchName"
                placeholder="请输入试卷名称"
                clearable
                style="width: 200px;"
                @clear="handleExamSearch"
              ></el-input>
            </el-form-item>
            <el-form-item label="试卷类型">
              <el-select
                v-model="examSearchType"
                placeholder="请选择类型"
                clearable
                style="width: 150px;"
                @clear="handleExamSearch"
              >
                <el-option label="随堂测验" :value="0"></el-option>
                <el-option label="考试" :value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="handleExamSearch">搜索</el-button>
              <el-button @click="handleExamReset">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 试卷表格 -->
        <el-table
          :data="papersList"
          border
          v-loading="papersLoading"
          element-loading-text="加载试卷列表中..."
          :highlight-current-row="currentTestIndex !== null"
          @selection-change="handleExamSelectionChange"
          @current-change="handleExamSelectionChange"
          max-height="400"
          ref="examTable"
        >
          <el-table-column
            v-if="currentTestIndex === null"
            type="selection"
            width="55"
            align="center"
          ></el-table-column>
          <el-table-column prop="id" label="试卷ID" width="80" align="center"></el-table-column>
          <el-table-column label="试卷名称" prop="name" min-width="200"></el-table-column>
          <el-table-column label="试卷类型" width="100" align="center">
            <template slot-scope="scope">
              <el-tag :type="getExamTypeTag(scope.row.type)" size="mini">
                {{ getExamTypeText(scope.row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="题目数量" width="100" align="center">
            <template slot-scope="scope">
              {{ scope.row.questions ? scope.row.questions.length : 0 }}题
            </template>
          </el-table-column>
          <el-table-column label="考试时间" width="120" align="center">
            <template slot-scope="scope">
              {{ scope.row.duration || scope.row.time || '-' }}分钟
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div style="margin-top: 16px; text-align: right;">
          <el-pagination
            @size-change="handleExamPageSizeChange"
            @current-change="handleExamPageChange"
            :current-page="examPagination.page"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="examPagination.page_size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="examPagination.total"
          >
          </el-pagination>
        </div>
      </div>
      <div slot="footer">
        <el-button @click="examSelectorVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmExamSelection" :disabled="selectedExamPapers.length === 0">
          确定选择 (已选择 {{ selectedExamPapers.length }} 张试卷)
        </el-button>
      </div>
    </el-dialog>

    <!-- 绑定学生对话框 -->
    <el-dialog
      title="绑定学生到课程"
      :visible.sync="bindStudentVisible"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="bind-student-container">
        <!-- 搜索框 -->
        <div class="bind-search mb-4">
          <el-input
            v-model="bindStudentSearchName"
            placeholder="搜索学生姓名"
            prefix-icon="el-icon-search"
            clearable
            style="width: 200px;"
            @keyup.enter.native="handleBindStudentSearch"
          ></el-input>
          <el-input
            v-model="bindStudentSearchPhone"
            placeholder="搜索电话"
            prefix-icon="el-icon-phone"
            clearable
            style="width: 200px; margin-left: 10px;"
            @keyup.enter.native="handleBindStudentSearch"
          ></el-input>
          <el-button 
            type="primary"
            icon="el-icon-search"
            @click="handleBindStudentSearch"
            style="margin-left: 10px;"
          >
            搜索
          </el-button>
        </div>

        <!-- 学生列表 -->
        <el-table
          ref="bindStudentTable"
          :data="filteredStudentList"
          border
          v-loading="studentListLoading"
          @selection-change="handleBindStudentSelection"
          max-height="450"
        >
          <el-table-column
            type="selection"
            width="55"
            align="center"
            :selectable="checkStudentSelectable"
          ></el-table-column>
          <el-table-column
            prop="id"
            label="学生ID"
            width="80"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="name"
            label="学生姓名"
            min-width="100"
          ></el-table-column>
          <el-table-column
            prop="phone"
            label="联系电话"
            min-width="120"
          ></el-table-column>
          <el-table-column
            label="状态"
            width="100"
            align="center"
          >
            <template slot-scope="scope">
              <el-tag
                size="small"
                :type="scope.row.isBind ? 'info' : 'success'"
              >
                {{ scope.row.isBind ? '已绑定' : '未绑定' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="100"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.isBind"
                type="text"
                size="small"
                @click="unbindStudentFromList(scope.row)"
                style="color: #F56C6C;"
              >
                解绑
              </el-button>
              <span v-else style="color: #909399;">-</span>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container" style="margin-top: 15px;">
          <el-pagination
            @size-change="handleBindStudentSizeChange"
            @current-change="handleBindStudentPageChange"
            :current-page="bindStudentPagination.page"
            :page-sizes="[10, 20, 50]"
            :page-size="bindStudentPagination.size"
            :total="bindStudentPagination.total"
            layout="total, sizes, prev, pager, next"
          ></el-pagination>
        </div>
      </div>
      
      <div slot="footer">
        <el-button @click="bindStudentVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="confirmBindStudents"
          :disabled="selectedBindStudents.length === 0"
        >
          确定绑定 ({{ selectedBindStudents.length }}人)
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import api from '@/api';

export default {
  data() {
    return {
      // 搜索表单
      searchForm: {
        keyword: '',
        category: '',
        status: ''
      },

      // 加载状态
      loading: false,

      // 课程列表数据
      courseList: [],

      // 分页配置
      pagination: {
        page: 1,
        size: 10,
        total: 12
      },

      // 模态框状态
      courseModalVisible: false,
      viewModalVisible: false,
      deleteVisible: false,
      questionSelectorVisible: false,
      examSelectorVisible: false,
      modalTitle: '新增课程',

      // 表单数据
      formData: {
        id: '',
        name: '',
        category: '',
        status: 'draft',
        description: '',
        trainingParams: {
          difficultyLevel: '',
          weldingJoint: '',
          weldingPosition: '',
          baseMaterial: '',
          thickness: '',
          weldingMethod: '',
          fillerMaterial: '',
          gasType: '',
          seamLength: '',
          weldingLayers: '',
          weldingCurrent: '',
          arcVoltage: '',
          weldingSpeed: '',
          preheatingTemp: '',
          interpassTemp: '',
          heatInput: '',
          wireSpeed: '',
          gasFlowRate: '',
          nozzleDistance: '',
          remarks: ''
        },
        learningContents: [
          { type: 'theory', contentId: '', name: '' }
        ],
        tests: [
          {
            name: '',
            time: 20,
            testType: 'quiz', // 'quiz' 或 'exam'
            paperId: '',
            questions: []
          }
        ]
      },

      // WPS列表数据
      wpsList: [],
      
      // 试题列表数据
      questionsList: [],
      
      // 试卷列表数据
      papersList: [],

      // 题目选择相关
      questionFilterType: '',
      selectedQuestions: [],
      currentTestIndex: null,
      questionsLoading: false, // 题库加载状态

      // 试卷选择相关
      selectedExamPaper: null, // 保留用于单个选择（兼容旧逻辑）
      selectedExamPapers: [], // 多选试卷列表
      papersLoading: false, // 试卷列表加载状态
      examSearchName: '', // 试卷搜索名称
      examSearchType: '', // 试卷搜索类型 (0=随堂测验, 1=考试)
      examPagination: {
        page: 1,
        page_size: 10,
        total: 0
      },

      // 绑定学生相关
      bindStudentVisible: false,
      bindStudentSearchName: '',
      bindStudentSearchPhone: '',
      selectedBindStudents: [],
      studentList: [], // 从API加载学生数据
      studentListLoading: false, // 学生列表加载状态
      courseDetailLoading: false, // 课程详情加载状态（编辑用）
      viewDetailLoading: false, // 查看详情加载状态
      bindStudentPagination: {
        page: 1,
        size: 10,
        total: 0
      },

      // 当前查看/删除的课程
      currentCourse: {},
      deleteCourse: {},

      // 内容选项数据源（模拟）
      theoryOptions: [],
      wpsOptions: [],

      // 课程分类选项(可输入可选择)
      categoryOptions: [],
      categoryList: [], // 完整的分类数据（包含id和name）

      // 可选试卷列表
      examPaperOptions: [],

      // 题库数据（扁平化为数组，带类型标记）
      fullQuestionBank: [],

      // 试卷列表数据（模拟）
      examPaperList: [],

      // 表单验证规则
      formRules: {
        name: [
          { required: true, message: '请输入课程名称', trigger: 'blur' },
          { min: 5, max: 100, message: '名称长度在5-100个字符之间', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择或输入课程分类', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择课程状态', trigger: 'change' }
        ]
      }
    };
  },
  mounted() {
    // 只加载课程列表和分类列表
    this.getCourseList();
    this.getCategories();
    
    // 确保formData.trainingParams存在
    if (!this.formData.trainingParams) {
      this.$set(this.formData, 'trainingParams', {
        difficultyLevel: '',
        weldingJoint: '',
        weldingPosition: '',
        baseMaterial: '',
        thickness: '',
        weldingMethod: '',
        fillerMaterial: '',
        gasType: '',
        seamLength: '',
        weldingLayers: '',
        weldingCurrent: '',
        arcVoltage: '',
        weldingSpeed: '',
        preheatingTemp: '',
        interpassTemp: '',
        heatInput: '',
        wireSpeed: '',
        gasFlowRate: '',
        nozzleDistance: '',
        remarks: ''
      });
    }
  },
  computed: {
    // 过滤后的题库
    filteredQuestionBank() {
      if (!this.questionFilterType) {
        return this.questionsList;
      }
      return this.questionsList.filter(q => q.type === this.questionFilterType);
    },

    // 过滤后的学生列表
    filteredStudentList() {
      // 搜索和分页已在后端处理，直接返回学生列表
      return this.studentList;
    }
  },
  methods: {
    // 将难度等级数字转换为文本
    getDifficultyText(level) {
      const map = { 1: '初级', 2: '中级', 3: '高级' };
      return map[level] || level;
    },
    
    // 格式化实训参数:后端字段 -> 前端字段
    formatTrainingParams(practicalParam) {
      if (!practicalParam) {
        return {
          difficultyLevel: '',
          weldingJoint: '',
          weldingPosition: '',
          baseMaterial: '',
          thickness: '',
          weldingMethod: '',
          fillerMaterial: '',
          gasType: '',
          seamLength: '',
          weldingLayers: '',
          weldingCurrent: '',
          arcVoltage: '',
          weldingSpeed: '',
          preheatingTemp: '',
          interpassTemp: '',
          heatInput: '',
          wireSpeed: '',
          gasFlowRate: '',
          nozzleDistance: '',
          remarks: ''
        };
      }
      
      return {
        difficultyLevel: practicalParam.difficulty || '',
        weldingJoint: practicalParam.weld_joint || '',
        weldingPosition: practicalParam.position || '',
        baseMaterial: practicalParam.material || '',
        thickness: practicalParam.thickness || '',
        weldingMethod: practicalParam.welding_method || '',
        fillerMaterial: practicalParam.filler_material || '',
        gasType: practicalParam.gas_type || '',
        seamLength: practicalParam.weld_length || '',
        weldingLayers: practicalParam.weld_layers || '',
        weldingCurrent: '',
        arcVoltage: '',
        weldingSpeed: '',
        preheatingTemp: '',
        interpassTemp: '',
        heatInput: '',
        wireSpeed: '',
        gasFlowRate: '',
        nozzleDistance: '',
        remarks: practicalParam.remark || ''
      };
    },
    
    // 获取课程列表
    async getCourseList() {
      try {
        this.loading = true;
        const params = {
          page: this.pagination.page,
          page_size: this.pagination.size
        };
        
        // 添加搜索参数
        if (this.searchForm.keyword) {
          params.name = this.searchForm.keyword;
        }
        if (this.searchForm.category) {
          params.category_id = this.searchForm.category;
        }
        if (this.searchForm.status !== '') {
          params.status = this.searchForm.status;
        }
        
        const response = await api.course.getCourseList(params);
        
        if (response.code === 200) {
          const list = Array.isArray(response.data?.list) ? response.data.list : (Array.isArray(response.data) ? response.data : []);
          
          // 数据映射:后端字段 -> 前端字段
          this.courseList = list.map(item => ({
            ...item,
            contentCount: item.knowledge_count || 0,
            quizCount: item.paper_count || 0,
            studentCount: item.student_count || 0,
            createTime: item.created_at
          }));
          
          // 兼容两种分页格式
          if (response.pagination) {
            this.pagination.total = response.pagination.total || 0;
          } else if (response.data) {
            this.pagination.total = response.data.total || 0;
          }
        } else {
          this.$message.error(response.message || '获取课程列表失败');
        }
      } catch (error) {
        this.$message.error('获取课程列表失败');
      } finally {
        this.loading = false;
      }
    },

    // 获取分类列表
    async getCategories() {
      try {
        const res = await api.course.getCourseCategories();
        if (res && res.code === 200) {
          const list = Array.isArray(res.data?.list) ? res.data.list : (Array.isArray(res.data) ? res.data : []);
          // 保存完整的分类数据（包含id和name）
          this.categoryList = list.map(item => {
            if (typeof item === 'object') {
              return {
                id: item.id,
                name: item.name || item.category_name || ''
              };
            } else {
              return {
                id: null,
                name: String(item)
              };
            }
          });
          
          // 同时保留原有的简单名称列表（用于下拉显示）
          this.categoryOptions = this.categoryList.map(item => item.name);
        }
      } catch (error) {
      }
    },

    // 获取可选知识列表
    async getAvailableKnowledges() {
      try {
        const res = await api.course.getAvailableKnowledges();
        if (res && res.code === 200) {
          const list = Array.isArray(res.data?.list) ? res.data.list : (Array.isArray(res.data) ? res.data : []);
          // 更新理论知识选项
          this.theoryOptions = list.map(item => ({
            id: item.id,
            name: item.title || item.name || ''
          }));
        }
      } catch (error) {
      }
    },

    // 获取可选WPS列表
    async getAvailableWps() {
      try {
        const res = await api.wps.getWpsList({ status: 1 }); // 只获取启用状态的WPS
        if (res && res.code === 200) {
          const list = Array.isArray(res.data?.list) ? res.data.list : (Array.isArray(res.data) ? res.data : []);
          this.wpsList = list.map(item => ({
            id: item.id,
            name: item.title || item.name || ''
          }));
        }
      } catch (error) {
      }
    },

    // 获取学生列表（支持分页和搜索）
    async getStudentList(params = {}) {
      try {
        this.studentListLoading = true;
        const requestParams = {
          status: 1, // 只获取启用状态的学生
          page: params.page || this.bindStudentPagination.page,
          page_size: params.page_size || this.bindStudentPagination.size,
          name: params.name || this.bindStudentSearchName || undefined,
          phone: params.phone || this.bindStudentSearchPhone || undefined
        };

        const res = await api.student.getStudentList(requestParams);
        if (res && res.code === 200) {
          const data = res.data;
          const list = Array.isArray(data?.list) ? data.list : (Array.isArray(data) ? data : []);
          
          this.studentList = list.map(item => ({
            id: item.id,
            name: item.name,
            phone: item.phone || '',
            username: item.username || '',
            className: item.class_name || '',
            isBind: false // 默认未绑定，会在打开绑定对话框时更新
          }));

          // 更新分页信息
          this.bindStudentPagination.total = data?.total || list.length;
          
          // 如果当前课程存在，更新绑定状态
          if (this.currentCourse?.id) {
            const boundStudentIds = this.currentCourse.students?.map(s => s.id) || [];
            this.studentList = this.studentList.map(student => ({
              ...student,
              isBind: boundStudentIds.includes(student.id)
            }));
          }
        }
      } catch (error) {
        this.$message.error('获取学生列表失败');
      } finally {
        this.studentListLoading = false;
      }
    },

    // 获取试题列表
    async getQuestions() {
      try {
        this.questionsLoading = true;
        const res = await api.question.getQuestionList({ status: 1 }); // 只获取启用状态的试题
        if (res && res.code === 200) {
          const list = Array.isArray(res.data?.list) ? res.data.list : (Array.isArray(res.data) ? res.data : []);
          this.questionsList = list.map(item => ({
            id: item.id,
            content: item.content || '',
            type: this.mapQuestionType(item.type), // 映射题型
            options: this.parseOptions(item.options),
            answer: item.answer || ''
          }));
        }
      } catch (error) {
      } finally {
        this.questionsLoading = false;
      }
    },

    // 映射题型:后端 1/2/3 -> 前端 single/multiple/judge
    mapQuestionType(type) {
      const typeMap = {
        1: 'single',
        2: 'multiple',
        3: 'judge'
      };
      return typeMap[type] || 'single';
    },

    // 解析选项(如果是JSON字符串则解析)
    parseOptions(options) {
      if (!options) return [];
      if (Array.isArray(options)) return options;
      try {
        return JSON.parse(options);
      } catch (e) {
        return [];
      }
    },

    // 获取试卷列表
    async getPapers() {
      try {
        this.papersLoading = true;
        
        // 构建查询参数
        const params = {
          status: 1, // 只获取启用状态的试卷
          page: this.examPagination.page,
          page_size: this.examPagination.page_size
        };
        
        // 添加搜索条件
        if (this.examSearchName) {
          params.name = this.examSearchName;
        }
        if (this.examSearchType !== '' && this.examSearchType !== null) {
          params.type = this.examSearchType;
        }
        
        const res = await api.exam.getExamList(params);
        if (res && res.code === 200) {
          // 处理数据列表
          const list = Array.isArray(res.data) ? res.data : (Array.isArray(res.data?.list) ? res.data.list : []);
          this.papersList = list.map(item => ({
            id: item.id,
            name: item.name || item.title || '',
            type: item.type,
            duration: item.duration || item.time || 60,
            questions: item.questions || []
          }));
          
          // 更新分页信息 - 从 pagination 对象获取
          if (res.pagination) {
            this.examPagination.total = res.pagination.total || 0;
            this.examPagination.page = res.pagination.page || 1;
          } else {
            // 兼容没有分页信息的情况
            this.examPagination.total = res.data?.total || list.length;
          }
        }
      } catch (error) {
        this.$message.error('获取试卷列表失败');
      } finally {
        this.papersLoading = false;
      }
    },

    // 获取试卷类型文本 (兼容多种格式: 0, '0', 'quiz', 1, '1', 'exam')
    getExamTypeText(type) {
      if (type === 0 || type === '0' || type === 'quiz') {
        return '随堂测验';
      } else if (type === 1 || type === '1' || type === 'exam') {
        return '考试';
      }
      return '未知';
    },

    // 获取试卷类型标签样式
    getExamTypeTag(type) {
      if (type === 0 || type === '0' || type === 'quiz') {
        return 'success';
      } else if (type === 1 || type === '1' || type === 'exam') {
        return 'warning';
      }
      return 'info';
    },

    // 获取可选试卷列表
    async getAvailablePapers() {
      try {
        const res = await api.course.getAvailablePapers();
        if (res && res.code === 200) {
          const list = Array.isArray(res.data?.list) ? res.data.list : (Array.isArray(res.data) ? res.data : []);
          // 更新试卷选项(用于随堂测验和考试)
          this.examPaperOptions = list.map(item => ({
            id: item.id,
            name: item.name || item.title || '',
            type: item.type || ''
          }));
        }
      } catch (error) {
      }
    },

    // 类型标签样式映射
    getTypeTagType(type) {
      const typeMap = {
        theory: 'info',
        practice: 'primary',
        comprehensive: 'success'
      };
      return typeMap[type] || 'default';
    },

    // 类型文本映射
    getTypeText(type) {
      // 兼容老数据,如果是预定义类型则翻译
      const typeMap = {
        theory: '理论课程',
        practice: '实操课程',
        comprehensive: '综合课程'
      };
      return typeMap[type] || type || '-';
    },

    // 检查是否有实训参数
    hasTrainingParams(params) {
      if (!params) return false;
      const keys = ['difficultyLevel', 'weldingJoint', 'weldingPosition', 'baseMaterial', 
                    'thickness', 'weldingMethod', 'fillerMaterial', 'gasType', 
                    'seamLength', 'weldingLayers', 'remarks'];
      return keys.some(key => params[key]);
    },

    // 状态文本映射
    getStatusText(status) {
      const statusMap = {
        '1': '启用',
        '0': '停用',
        1: '启用',
        0: '停用',
        active: '启用',
        disabled: '停用'
      };
      return statusMap[status] || '未知状态';
    },

    // 题目类型文本映射
    getQuestionTypeText(type) {
      const typeMap = {
        single: '单选题',
        multiple: '多选题',
        judge: '判断题'
      };
      return typeMap[type] || '未知题型';
    },

    // 获取内容选项
    getContentOptions(type) {
      if (type === 'theory') {
        return this.theoryOptions;
      } else if (type === 'wps') {
        // 使用从API获取的WPS列表
        return this.wpsList.map(item => ({
          id: item.id,
          name: item.name
        }));
      }
      return [];
    },

    // 打开新增/编辑抽屉
    openCourseModal(row, event) {
      // 阻止事件冒泡（避免触发行点击）
      if (event) event.stopPropagation();
      
      if (row) {
        // 编辑模式
        this.modalTitle = '编辑课程';
        // 先设置一个空的formData避免表单报错
        this.formData = {
          id: row.id,
          name: '',
          number: '',
          category: '',
          status: 'active',
          description: '',
          trainingParams: {
            difficultyLevel: '',
            weldingJoint: '',
            weldingPosition: '',
            baseMaterial: '',
            thickness: '',
            weldingMethod: '',
            fillerMaterial: '',
            gasType: '',
            seamLength: '',
            weldingLayers: '',
            weldingCurrent: '',
            arcVoltage: '',
            weldingSpeed: '',
            preheatingTemp: '',
            interpassTemp: '',
            heatInput: '',
            wireSpeed: '',
            gasFlowRate: '',
            nozzleDistance: '',
            remarks: ''
          },
          learningContents: [],
          tests: []
        };
      } else {
        // 新增模式
        this.modalTitle = '新增课程';
        this.formData = {
          id: '',
          name: '',
          number: '',
          category: '',
          status: 'active',
          description: '',
          trainingParams: {
            difficultyLevel: '',
            weldingJoint: '',
            weldingPosition: '',
            baseMaterial: '',
            thickness: '',
            weldingMethod: '',
            fillerMaterial: '',
            gasType: '',
            seamLength: '',
            weldingLayers: '',
            weldingCurrent: '',
            arcVoltage: '',
            weldingSpeed: '',
            preheatingTemp: '',
            interpassTemp: '',
            heatInput: '',
            wireSpeed: '',
            gasFlowRate: '',
            nozzleDistance: '',
            remarks: ''
          },
          learningContents: [
            { type: 'theory', contentId: '', name: '' }
          ],
          classQuizzes: [
            {
              name: '',
              time: 20,
              questions: []
            }
          ],
          exams: [
            {
              name: '',
              time: 60,
              questions: []
            }
          ]
        };
      }
      
      // 先打开对话框
      this.courseModalVisible = true;
      
      this.$nextTick(() => {
        // 清除验证
        this.$refs.courseForm && this.$refs.courseForm.clearValidate();
      });
      
      // 异步加载理论知识和WPS数据
      if (this.theoryOptions.length === 0) {
        this.getAvailableKnowledges();
      }
      if (this.wpsList.length === 0) {
        this.getAvailableWps();
      }
      
      // 如果是编辑模式，异步加载课程详情
      if (row) {
        this.loadCourseDetail(row);
      }
    },
    
    // 异步加载课程详情
    async loadCourseDetail(row) {
      this.courseDetailLoading = true;
      try {
        const data = await this.formatCourseData(row);
        if (data && data.id) {
          // 确保 trainingParams 存在
          if (!data.trainingParams) {
            data.trainingParams = {
              difficultyLevel: '',
              weldingJoint: '',
              weldingPosition: '',
              baseMaterial: '',
              thickness: '',
              weldingMethod: '',
              fillerMaterial: '',
              gasType: '',
              seamLength: '',
              weldingLayers: '',
              weldingCurrent: '',
              arcVoltage: '',
              weldingSpeed: '',
              preheatingTemp: '',
              interpassTemp: '',
              heatInput: '',
              wireSpeed: '',
              gasFlowRate: '',
              nozzleDistance: '',
              remarks: ''
            };
          }
          // 确保 learningContents 存在
          if (!data.learningContents || !Array.isArray(data.learningContents)) {
            data.learningContents = [];
          }
          // 确保 tests 存在
          if (!data.tests || !Array.isArray(data.tests)) {
            data.tests = [];
          }
          this.formData = data;
        }
      } finally {
        this.courseDetailLoading = false;
      }
    },

    // 格式化课程数据（编辑/查看用）
    async formatCourseData(row) {
      // 从接口获取完整课程数据
      try {
        const res = await api.course.getCourseDetail(row.id);
        if (res && res.code === 200) {
          const data = res.data || {};
          
          // 处理分类名称
          let categoryName = '';
          if (data.category) {
            categoryName = typeof data.category === 'object' ? data.category.name : data.category;
          } else if (data.category_name) {
            categoryName = data.category_name;
          }
          
          // 处理学习内容 - 将 knowledges 转换为 learningContents
          const learningContents = [];
          if (Array.isArray(data.knowledges)) {
            data.knowledges.forEach(item => {
              // 根据 is_wps 字段判断是 WPS 还是理论知识
              const contentType = item.is_wps ? 'wps' : 'theory';
              
              learningContents.push({
                type: contentType,
                contentId: item.id,
                name: item.title || item.name || ''
              });
            });
          }
          
          // 处理试卷 - 将 papers 转换为 tests
          // 注意: 课程详情接口返回的papers不包含questions,需要通过试卷列表接口获取完整数据
          const tests = [];
          if (Array.isArray(data.papers) && data.papers.length > 0) {
            try {
              // 获取所有试卷列表(包含题目信息)
              const examListRes = await api.exam.getExamList({ page_size: 9999 });
              
              if (examListRes && examListRes.code === 200) {
                // 兼容不同的数据格式: data.list 或 data.data 或 data
                const examList = Array.isArray(examListRes.data?.list) 
                  ? examListRes.data.list 
                  : (Array.isArray(examListRes.data?.data) 
                    ? examListRes.data.data 
                    : (Array.isArray(examListRes.data) ? examListRes.data : []));
                
                // 建立试卷ID到完整试卷信息的映射
                const examMap = new Map();
                examList.forEach(exam => {
                  examMap.set(exam.id, exam);
                });
                
                // 处理课程中的每个试卷
                data.papers.forEach(paper => {
                  const examDetail = examMap.get(paper.id);
                  
                  // 处理试卷的题目列表
                  const questions = [];
                  if (examDetail && Array.isArray(examDetail.questions)) {
                    examDetail.questions.forEach(question => {
                      questions.push({
                        id: question.id,
                        type: this.mapQuestionType(question.type),
                        content: question.content || ''
                      });
                    });
                  }
                  
                  tests.push({
                    _uid: Date.now() + Math.random() + tests.length, // 添加唯一ID
                    name: paper.name || '',
                    time: paper.duration || 60,
                    testType: (paper.type === 1 || paper.type === '1') ? 'exam' : 'quiz', // 优先使用后端返回的type, 1:考试, 0:随堂测验
                    paperId: paper.id,
                    questions: questions // 包含题目详情用于回显
                  });
                });
              }
            } catch (err) {
              // 如果获取失败,至少保留试卷基本信息
              data.papers.forEach((paper, idx) => {
                tests.push({
                  _uid: Date.now() + Math.random() + idx, // 添加唯一ID
                  name: paper.name || '',
                  time: paper.duration || 60,
                  testType: (paper.type === 1 || paper.type === '1') ? 'exam' : 'quiz', // 使用后端返回的type
                  paperId: paper.id,
                  questions: []
                });
              });
            }
          }
          
          // 映射后端字段到前端字段
          const formattedData = {
            id: data.id,
            name: data.name || '',
            number: data.code || data.number || '',
            category: categoryName,
            status: data.status === 1 || data.status === 'active' ? 'active' : 'disabled',
            description: data.description || '',
            trainingParams: this.formatTrainingParams(data.practical_param),
            learningContents: learningContents,
            tests: tests,
            students: data.students || [],
            bindStudents: data.students || []
          };
          
          return formattedData;
        }
      } catch (error) {
        this.$message.error('获取课程详情失败');
      }
      return {};
    },

    // 打开查看模态框
    openViewModal(row, event) {
      if (event) event.stopPropagation();
      
      // 先打开对话框
      this.viewModalVisible = true;
      
      // 初始化为空数据
      this.currentCourse = {
        id: row.id,
        name: row.name || '',
        category: {},
        knowledges: [],
        papers: [],
        students: []
      };
      
      // 异步加载详情数据
      this.loadViewDetail(row);
    },
    
    // 异步加载查看详情数据
    async loadViewDetail(row) {
      this.viewDetailLoading = true;
      try {
        const data = await this.formatCourseData(row);
        if (data && data.id) {
          // Ensure `currentCourse.category` is an object for the view template
          // (template uses `currentCourse.category?.name`). formatCourseData
          // returns category as a string for edit form usage, so wrap it here.
          if (data && typeof data.category === 'object') {
            this.currentCourse = data;
          } else {
            this.currentCourse = {
              ...data,
              category: {
                name: data.category || '',
                id: data.category_id || (data.category && data.category.id) || null
              }
            };
          }
        }
      } finally {
        this.viewDetailLoading = false;
      }
    },

    // 启用/停用课程
    async handleStatusToggle(row, event) {
      if (event) event.stopPropagation();
      
      const newStatus = row.status === 1 ? 0 : 1;
      const statusText = newStatus === 1 ? '启用' : '停用';
      
      // 弹窗确认
      try {
        await this.$confirm(`确定要${statusText}课程「${row.name}」吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
      } catch {
        // 用户取消操作
        return;
      }
      
      try {
        // 获取完整的课程数据
        const detailRes = await api.course.getCourseDetail(row.id);
        if (!detailRes || detailRes.code !== 200) {
          this.$message.error('获取课程详情失败');
          return;
        }
        
        const courseData = detailRes.data;
        
        // 收集知识点ID
        const knowledgeIds = [];
        if (Array.isArray(courseData.knowledges)) {
          courseData.knowledges.forEach(item => {
            knowledgeIds.push(item.id);
          });
        }
        
        // 收集试卷数据
        const papers = [];
        if (Array.isArray(courseData.papers)) {
          // 获取试卷列表以获得完整的试卷信息
          const examListRes = await api.exam.getExamList({ page_size: 9999 });
          const examMap = new Map();
          
          if (examListRes && examListRes.code === 200) {
            const examList = Array.isArray(examListRes.data?.list) 
              ? examListRes.data.list 
              : (Array.isArray(examListRes.data?.data) 
                ? examListRes.data.data 
                : (Array.isArray(examListRes.data) ? examListRes.data : []));
            
            examList.forEach(exam => {
              examMap.set(exam.id, exam);
            });
          }
          
          courseData.papers.forEach(paper => {
            const examDetail = examMap.get(paper.id);
            if (examDetail) {
              papers.push({
                id: paper.id,
                name: paper.name || examDetail.name || '',
                duration: paper.duration || examDetail.duration || 60,
                type: examDetail.type === 1 ? 1 : 0,
                question_ids: Array.isArray(examDetail.questions) ? examDetail.questions.map(q => q.id) : []
              });
            } else {
              papers.push({ id: paper.id });
            }
          });
        }
        
        // 构建提交数据
        const submitData = {
          id: row.id,
          name: courseData.name,
          status: newStatus,
          knowledge_ids: knowledgeIds,
          papers: papers
        };
        
        // 添加分类
        if (courseData.category_id) {
          submitData.category_id = courseData.category_id;
        }
        
        // 添加实训参数
        if (courseData.practical_param && courseData.practical_param.difficulty) {
          const params = courseData.practical_param;
          submitData.practical_param = {
            difficulty: parseInt(params.difficulty)
          };
          
          if (params.weld_joint) submitData.practical_param.weld_joint = params.weld_joint;
          if (params.position) submitData.practical_param.position = params.position;
          if (params.material) submitData.practical_param.material = params.material;
          if (params.thickness) submitData.practical_param.thickness = parseFloat(params.thickness);
          if (params.welding_method) submitData.practical_param.welding_method = params.welding_method;
          if (params.filler_material) submitData.practical_param.filler_material = params.filler_material;
          if (params.gas_type) submitData.practical_param.gas_type = params.gas_type;
          if (params.weld_length) submitData.practical_param.weld_length = parseFloat(params.weld_length);
          if (params.weld_layers) submitData.practical_param.weld_layers = parseInt(params.weld_layers);
          if (params.remark) submitData.practical_param.remark = params.remark;
        }
        
        // 调用更新接口
        const res = await api.course.updateCourse(submitData);
        if (res && res.code === 200) {
          this.$message.success(`课程已${statusText}`);
          this.getCourseList();
        }
      } catch (error) {
        this.$message.error(`${statusText}课程失败`);
      }
    },
    
    // 打开删除确认弹窗
    openDeleteConfirm(row, event) {
      if (event) event.stopPropagation();
      this.deleteCourse = row;
      this.deleteVisible = true;
    },

    // 确认删除
    async confirmDelete() {
      try {
        const res = await api.course.deleteCourse(this.deleteCourse.id);
        if (res && res.code === 200) {
          // 删除成功，刷新列表
          this.$message.success(`已成功删除课程「${this.deleteCourse.name}」`);
          this.deleteVisible = false;
          this.getCourseList();
        }
      } catch (error) {
        this.$message.error(error.message || '删除课程失败');
      }
    },

    // 表格行点击（查看详情）
    handleRowClick(row) {
      // 先打开对话框
      this.viewModalVisible = true;
      
      // 初始化为空数据
      this.currentCourse = {
        id: row.id,
        name: row.name || '',
        category: {},
        knowledges: [],
        papers: [],
        students: []
      };
      
      // 异步加载详情数据
      this.loadViewDetail(row);
    },

    // 添加学习内容
    addLearningContent() {
      // 调试日志，确保方法被调用
      // 有时表单对象可能在外部被替换，先确保 learningContents 存在
      if (!this.formData) {
        return;
      }
      if (!Array.isArray(this.formData.learningContents)) {
        // 使用 $set 保持响应式
        this.$set(this.formData, 'learningContents', []);
      }

      const newItem = {
        type: 'theory', // 默认为理论知识，用户可以通过下拉选择修改
        contentId: '',
        name: ''
      };

      this.formData.learningContents.push(newItem);

      // 兼容性措施：再次确保数组是响应式（通常 push 已生效）
      this.$set(this.formData, 'learningContents', this.formData.learningContents);
      this.$message && this.$message.success && this.$message.success('已添加学习内容');
    },

    // 删除学习内容
    deleteLearningContent(index) {
      if (!this.formData.learningContents || this.formData.learningContents.length <= 1) {
        this.$message.warning('至少保留一个学习内容');
        return;
      }
      this.formData.learningContents.splice(index, 1);
    },

    // 切换内容类型
    changeContent_type(index) {
      const content = this.formData.learningContents[index];
      content.contentId = '';
      content.name = '';
    },

    // 添加测验/考试 - 直接打开试卷选择对话框
    addTest() {
      if (!this.formData) {
        return;
      }
      if (!Array.isArray(this.formData.tests)) {
        this.$set(this.formData, 'tests', []);
      }

      // 重置选择状态
      this.selectedExamPapers = [];
      this.currentTestIndex = null; // 设置为null表示是批量添加模式
      
      // 重置搜索和分页
      this.examSearchName = '';
      this.examSearchType = '';
      this.examPagination.page = 1;
      
      // 打开试卷选择对话框
      this.examSelectorVisible = true;
      
      // 加载试卷列表
      this.getPapers();
    },

    // 删除测验/考试
    deleteTest(index) {
      this.formData.tests.splice(index, 1);
    },

    // 删除题目
    deleteQuestion(testIndex, questionIndex) {
      const targetTest = this.formData.tests[testIndex];
      if (targetTest && Array.isArray(targetTest.questions)) {
        const updatedQuestions = [...targetTest.questions];
        updatedQuestions.splice(questionIndex, 1);
        this.$set(this.formData.tests[testIndex], 'questions', updatedQuestions);
      }
    },

    // 打开题目选择器
    openQuestionSelector(testIndex) {
      this.currentTestIndex = testIndex;
      this.questionFilterType = '';
      this.selectedQuestions = [];
      
      // 先打开对话框
      this.questionSelectorVisible = true;
      
      this.$nextTick(() => {
        this.$refs.questionSelectorTable && this.$refs.questionSelectorTable.clearSelection();
      });
      
      // 异步加载题库数据
      if (this.questionsList.length === 0) {
        this.getQuestions();
      }
    },

    // 打开试卷选择器（单个编辑模式）
    openExamSelector(testIndex) {
      this.currentTestIndex = testIndex;
      this.selectedExamPaper = null;
      this.selectedExamPapers = [];
      
      // 重置搜索和分页
      this.examSearchName = '';
      this.examSearchType = '';
      this.examPagination.page = 1;
      
      // 先打开对话框
      this.examSelectorVisible = true;
      
      // 加载试卷列表
      this.getPapers();
      
      // 清空表格选择
      this.$nextTick(() => {
        if (this.$refs.examTable) {
          this.$refs.examTable.clearSelection();
        }
      });
    },

    // 试卷搜索
    handleExamSearch() {
      this.examPagination.page = 1; // 重置到第一页
      this.getPapers();
    },

    // 试卷搜索重置
    handleExamReset() {
      this.examSearchName = '';
      this.examSearchType = '';
      this.examPagination.page = 1;
      this.getPapers();
    },

    // 试卷分页 - 每页条数改变
    handleExamPageSizeChange(size) {
      this.examPagination.page_size = size;
      this.examPagination.page = 1; // 重置到第一页
      this.getPapers();
    },

    // 试卷分页 - 页码改变
    handleExamPageChange(page) {
      this.examPagination.page = page;
      this.getPapers();
    },

    // 题目选择变化
    handleQuestionSelectionChange(selection) {
      this.selectedQuestions = selection;
    },

    // 试卷选择变化（支持多选）
    async handleExamSelectionChange(selection) {
      if (Array.isArray(selection)) {
        // 多选模式
        this.selectedExamPapers = selection.map(paper => ({ ...paper }));
        
        // 为每个选中的试卷获取题目详情
        for (let paper of this.selectedExamPapers) {
          if (!paper.questions || paper.questions.length === 0) {
            try {
              const res = await api.exam.getPaperQuestions({ paper_id: paper.id });
              if (res && res.code === 200) {
                const questions = Array.isArray(res.data?.list) ? res.data.list : (Array.isArray(res.data) ? res.data : []);
                paper.questions = questions.map(item => ({
                  id: item.id,
                  type: this.mapQuestionType(item.type),
                  content: item.content || item.question || ''
                }));
              }
            } catch (error) {
            }
          }
        }
      } else if (selection) {
        // 单选模式（兼容旧逻辑）
        this.selectedExamPaper = { ...selection };
        
        // 如果选择了试卷且没有题目详情，则获取题目详情
        if (!this.selectedExamPaper.questions || this.selectedExamPaper.questions.length === 0) {
          try {
            const res = await api.exam.getPaperQuestions({ paper_id: this.selectedExamPaper.id });
            if (res && res.code === 200) {
              const questions = Array.isArray(res.data?.list) ? res.data.list : (Array.isArray(res.data) ? res.data : []);
              this.selectedExamPaper.questions = questions.map(item => ({
                id: item.id,
                type: this.mapQuestionType(item.type),
                content: item.content || item.question || ''
              }));
            }
          } catch (error) {
            this.$message.error('获取试卷题目失败');
          }
        }
      } else {
        // 清空选择
        this.selectedExamPaper = null;
        this.selectedExamPapers = [];
      }
    },

    // 确认题目选择
    confirmQuestionSelection() {
      if (this.selectedQuestions.length === 0) {
        this.$message.warning('请至少选择一道题目');
        return;
      }

      const targetTest = this.formData.tests[this.currentTestIndex];
      
      if (!targetTest) {
        this.$message.error('目标测验/考试不存在');
        return;
      }

      // 使用题目生成试卷，覆盖已有的题目或试卷
      const newQuestions = this.selectedQuestions.map(q => ({
        id: q.id,
        type: q.type,
        content: q.content
      }));

      // 直接替换题目列表（覆盖模式）
      this.$set(this.formData.tests[this.currentTestIndex], 'questions', newQuestions);
      // 清空试卷ID（如果之前选了试卷）
      this.$set(this.formData.tests[this.currentTestIndex], 'paperId', '');

      this.$message.success(`已选择 ${newQuestions.length} 道题目（覆盖原有内容）`);
      this.questionSelectorVisible = false;
    },

    // 确认试卷选择
    async confirmExamSelection() {
      // 判断是批量添加模式还是单个编辑模式
      if (this.currentTestIndex === null) {
        // 批量添加模式：为每个选中的试卷创建一个测验/考试
        if (this.selectedExamPapers.length === 0) {
          this.$message.warning('请至少选择一张试卷');
          return;
        }

        // 为每个选中的试卷创建测验/考试项
        const newTests = [];
        for (let paper of this.selectedExamPapers) {
          // 确定测验类型
          let testType = 'quiz'; // 默认为随堂测验
          if (paper.type === 1 || paper.type === '1' || paper.type === 'exam') {
            testType = 'exam';
          }

          // 创建新的测验/考试项
          const newTest = {
            _uid: Date.now() + Math.random() + paper.id, // 添加唯一ID
            name: paper.name || paper.title || '',
            time: paper.duration || paper.time || 20,
            testType: testType,
            paperId: paper.id,
            questions: paper.questions ? paper.questions.map(q => ({
              id: q.id,
              type: this.mapQuestionType(q.type),
              content: q.content
            })) : []
          };

          newTests.push(newTest);
        }

        // 批量添加到tests数组
        this.formData.tests.push(...newTests);
        this.$message.success(`已添加 ${newTests.length} 个测验/考试`);
        this.examSelectorVisible = false;
        this.selectedExamPapers = [];
        
        // 清空表格选择
        if (this.$refs.examTable) {
          this.$refs.examTable.clearSelection();
        }
      } else {
        // 单个编辑模式（兼容旧逻辑）
        if (!this.selectedExamPaper) {
          this.$message.warning('请选择一张试卷');
          return;
        }

        const targetTest = this.formData.tests[this.currentTestIndex];
        
        if (!targetTest) {
          this.$message.error('目标测验/考试不存在');
          return;
        }

        // 使用试卷，覆盖已有的题目、名称、时长和类型
        this.$set(this.formData.tests[this.currentTestIndex], 'paperId', this.selectedExamPaper.id);
        // 自动填入试卷名称（覆盖原有名称）
        this.$set(this.formData.tests[this.currentTestIndex], 'name', this.selectedExamPaper.name || this.selectedExamPaper.title);
        // 自动填入试卷时长
        if (this.selectedExamPaper.duration) {
          this.$set(this.formData.tests[this.currentTestIndex], 'time', this.selectedExamPaper.duration);
        }
        // 自动填入试卷类型 (兼容多种格式: 0/'0'/'quiz' -> 'quiz', 1/'1'/'exam' -> 'exam')
        if (this.selectedExamPaper.type !== undefined && this.selectedExamPaper.type !== null) {
          let testType = 'quiz'; // 默认为随堂测验
          if (this.selectedExamPaper.type === 1 || this.selectedExamPaper.type === '1' || this.selectedExamPaper.type === 'exam') {
            testType = 'exam';
          }
          this.$set(this.formData.tests[this.currentTestIndex], 'testType', testType);
        }
        
        // 同时保存试卷的题目列表用于显示
        if (this.selectedExamPaper.questions && this.selectedExamPaper.questions.length > 0) {
          const questions = this.selectedExamPaper.questions.map(q => ({
            id: q.id,
            type: this.mapQuestionType(q.type),
            content: q.content
          }));
          
          this.$set(this.formData.tests[this.currentTestIndex], 'questions', questions);
          
          this.$message.success(`已选择试卷「${this.selectedExamPaper.name}」（覆盖原有内容）`);
        } else {
          this.$message.warning('该试卷没有题目');
          this.$set(this.formData.tests[this.currentTestIndex], 'questions', []);
        }

        this.examSelectorVisible = false;
        this.selectedExamPaper = null;
      }
    },

    // 保存课程
    saveCourse() {
      this.$refs.courseForm.validate(async valid => {
        if (valid) {
          try {
            // 收集知识点ID (包括理论知识theory和WPS，都存储在knowledge_ids中)
            const knowledgeIds = this.formData.learningContents
              .filter(content => content.contentId) // 过滤掉没有选择内容的项
              .map(content => content.contentId);

            // 收集试卷数据
            const papers = [];
            if (Array.isArray(this.formData.tests)) {
              this.formData.tests.forEach(test => {
                if (test.paperId) {
                  // 从题库选择的已有试卷，只传id
                  papers.push({ id: test.paperId });
                } else if (Array.isArray(test.questions) && test.questions.length > 0) {
                  // 自定义试卷，需要传完整信息
                  // 确保 type 是数字: 1=考试, 0=随堂测验
                  let typeValue = 0;
                  if (test.testType === 'exam' || test.testType === 1 || test.testType === '1') {
                    typeValue = 1;
                  }
                  
                  papers.push({
                    name: test.name || '自定义试卷',
                    duration: test.time || 60, // 考试时长
                    type: typeValue,
                    question_ids: test.questions.map(q => q.id)
                  });
                }
              });
            }

            // 构建提交数据
            const submitData = {
              name: this.formData.name,
              status: this.formData.status === 'active' ? 1 : 0,
              knowledge_ids: knowledgeIds,
              papers: papers
            };

            // 添加实训操作参数 - 转换为后端接口字段名
            // 注意: difficulty 是必填字段(1=初级,2=中级,3=高级),只有当 difficulty 有值时才传递 practical_param
            if (this.formData.trainingParams && this.formData.trainingParams.difficultyLevel) {
              const params = this.formData.trainingParams;
              
              submitData.practical_param = {
                difficulty: parseInt(params.difficultyLevel)
              };
              
              // 添加其他可选字段
              if (params.weldingJoint) submitData.practical_param.weld_joint = params.weldingJoint;
              if (params.weldingPosition) submitData.practical_param.position = params.weldingPosition;
              if (params.baseMaterial) submitData.practical_param.material = params.baseMaterial;
              if (params.thickness) submitData.practical_param.thickness = parseFloat(params.thickness);
              if (params.weldingMethod) submitData.practical_param.welding_method = params.weldingMethod;
              if (params.fillerMaterial) submitData.practical_param.filler_material = params.fillerMaterial;
              if (params.gasType) submitData.practical_param.gas_type = params.gasType;
              if (params.seamLength) submitData.practical_param.weld_length = parseFloat(params.seamLength);
              if (params.weldingLayers) submitData.practical_param.weld_layers = parseInt(params.weldingLayers);
              if (params.remarks) submitData.practical_param.remark = params.remarks;
            }

            // 分类处理: 如果选择的是现有分类传category_id, 如果是新输入的分类传category
            if (this.formData.category) {
              // 在分类列表中查找是否存在该分类
              const existingCategory = this.categoryList.find(cat => cat.name === this.formData.category);
              
              if (existingCategory && existingCategory.id) {
                // 现有分类,传category_id
                submitData.category_id = existingCategory.id;
              } else {
                // 新增分类,传category（分类名称）
                submitData.category = this.formData.category;
              }
            }

            const isEdit = !!this.formData.id;
            
            if (isEdit) {
              // 编辑模式
              submitData.id = this.formData.id;
              await api.course.updateCourse(submitData);
              this.$message.success('课程编辑成功');
            } else {
              // 新增模式
              await api.course.createCourse(submitData);
              this.$message.success('课程新增成功');
            }
            
            this.courseModalVisible = false;
            this.getCourseList(); // 刷新列表
            
          } catch (error) {
            this.$message.error('保存课程失败');
          }
        }
      });
    },

    // 搜索方法
    handleSearch() {
      this.pagination.page = 1;
      this.getCourseList();
    },

    // 重置方法
    handleReset() {
      this.searchForm = {
        keyword: '',
        category: '',
        status: ''
      };
      this.pagination.page = 1;
      this.getCourseList();
    },

    // 分页相关方法
    handleSizeChange(size) {
      this.pagination.size = size;
      this.pagination.page = 1;
      this.getCourseList();
    },
    handleCurrentChange(page) {
      this.pagination.page = page;
      this.getCourseList();
    },

    // 打开绑定学生对话框
    openBindStudentDialog() {
      this.bindStudentSearchName = '';
      this.bindStudentSearchPhone = '';
      this.selectedBindStudents = [];
      
      // 重置分页
      this.bindStudentPagination.page = 1;
      
      // 先打开对话框
      this.bindStudentVisible = true;
      
      this.$nextTick(() => {
        if (this.$refs.bindStudentTable) {
          this.$refs.bindStudentTable.clearSelection();
        }
      });
      
      // 异步加载学生列表
      this.getStudentList();
    },

    // 从列表打开学生绑定对话框
    openStudentListModal(row, event) {
      event.stopPropagation();
      this.currentCourse = { ...row };
      this.studentList = [];
      this.openBindStudentDialog();
    },

    // 检查学生是否可选择（只能选择未绑定的学生）
    checkStudentSelectable(row) {
      return !row.isBind;
    },

    // 学生选择变化
    handleBindStudentSelection(selection) {
      this.selectedBindStudents = selection;
    },

    // 确认绑定学生
    async confirmBindStudents() {
      if (this.selectedBindStudents.length === 0) {
        this.$message.warning('请选择要绑定的学生');
        return;
      }

      try {
        // 过滤出未绑定的学生
        const unbindStudents = this.selectedBindStudents.filter(student => !student.isBind);
        
        if (unbindStudents.length === 0) {
          this.$message.warning('所选学生已全部绑定');
          return;
        }

        // 使用学生绑定课程API
        const bindPromises = unbindStudents.map(student => 
          api.student.bindCourse({
            student_id: student.id,
            course_id: this.currentCourse.id,
            start_time: new Date().toISOString().slice(0, 19).replace('T', ' ')
          })
        );

        await Promise.all(bindPromises);

        this.$message.success(`成功绑定 ${unbindStudents.length} 名学生`);
        this.bindStudentVisible = false;
        
        // 刷新课程列表以更新学生数量
        this.getCourseList();
        
        // 重新加载学生列表
        // this.getStudentList();
      } catch (error) {
        this.$message.error(error.message || '绑定学生失败');
      }
    },

    // 解绑学生（从绑定学生列表中）
    async unbindStudent(student) {
      try {
        await this.$confirm(`确定要解除学生 ${student.name} 与该课程的绑定吗？`, '提示', {
          type: 'warning'
        });

        // 使用学生解绑课程API
        await api.student.unbindCourse({
          student_id: student.id,
          course_id: this.currentCourse.id
        });

        this.$message.success('解绑成功');
        
        // 从当前显示的绑定学生列表中移除
        const index = this.currentCourse.bindStudents.findIndex(s => s.id === student.id);
        if (index > -1) {
          this.currentCourse.bindStudents.splice(index, 1);
        }
        
        // 刷新课程列表以更新学生数量
        this.getCourseList();
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(error.message || '解绑学生失败');
        }
      }
    },

    // 从绑定学生对话框列表中解绑
    async unbindStudentFromList(student) {
      try {
        await this.$confirm(`确定要解除学生 ${student.name} 与该课程的绑定吗？`, '提示', {
          type: 'warning'
        });

        // 使用学生解绑课程API
        await api.student.unbindCourse({
          student_id: student.id,
          course_id: this.currentCourse.id
        });

        this.$message.success('解绑成功');
        student.isBind = false; // 更新列表中的绑定状态
        
        // 重新加载学生列表，更新绑定状态
        // this.getStudentList();
        
        // 刷新课程列表以更新学生数量
        this.getCourseList();
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(error.message || '解绑学生失败');
        }
      }
    },

    // 学生列表搜索
    handleBindStudentSearch() {
      this.bindStudentPagination.page = 1; // 重置到第一页
      this.getStudentList();
    },

    // 学生列表分页 - 每页数量变化
    handleBindStudentSizeChange(size) {
      this.bindStudentPagination.size = size;
      this.bindStudentPagination.page = 1;
      this.getStudentList();
    },

    // 学生列表分页 - 页码变化
    handleBindStudentPageChange(page) {
      this.bindStudentPagination.page = page;
      this.getStudentList();
    }
  }
};
</script>

<style scoped>
/* 页面标题 */
.page-header {
  margin-bottom: 20px;
  text-align: left;
}
.title {
  font-size: 20px;
  font-weight: bold;
  color: #304156;
  margin-bottom: 5px;
}
.desc {
  color: #86909C;
  font-size: 14px;
}

/* 搜索区 */
.search-card {
  padding: 15px 20px;
}
.search-container {
  width: 100%;
}

/* 清除浮动 */
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

/* 表格头部操作栏 */
.table-header {
  margin-bottom: 16px;
}

/* 课程列表样式 */
.course-status-tag {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}
.course-status-active {
  background-color: #D1FAE5;
  color: #059669;
  border-color: #D1FAE5;
}
.course-status-draft {
  background-color: #FFF7E6;
  color: #FF7D00;
  border-color: #FFF7E6;
}
.course-status-disabled {
  background-color: #F3F4F6;
  color: #6B7280;
  border-color: #F3F4F6;
}

/* 分页容器 */
.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 模态框样式 */
.course-modal {
  --form-item-margin: 16px;
}
.modal-grid {
  width: 100%;
  padding: 10px 0;
}
.form-item {
  margin-bottom: var(--form-item-margin) !important;
}
.full-width {
  width: 100% !important;
}

/* 课程内容区域样式 */
.content-header {
  margin-bottom: 16px;
}
.content-title {
  font-size: 16px;
  font-weight: 500;
  color: #304156;
  margin-bottom: 8px;
}

/* 章节样式 */
.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}
.section-icon {
  color: #165DFF;
  margin-right: 8px;
  font-size: 16px;
}
.section-title {
  font-size: 14px;
  font-weight: 500;
  color: #304156;
  margin-right: 12px;
}
.section-desc {
  font-size: 12px;
  color: #86909C;
}
.section-content {
  background-color: #F9FAFB;
  padding: 16px;
  border-radius: 4px;
}

/* 内容操作栏 */
.content-operation {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}
.content-label {
  font-size: 13px;
  font-weight: 500;
  color: #4E5969;
}
.content-buttons {
  display: flex;
  gap: 8px;
}

/* 学习内容表格 */
.learning-table {
  background-color: #FFFFFF;
}
.content-select {
  width: 100%;
}

/* 测验项目样式 */
.quiz-item {
  background-color: #FFFFFF;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  padding: 16px;
  margin-bottom: 12px;
}
.quiz-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}
.quiz-title {
  font-size: 13px;
  font-weight: 500;
  color: #304156;
}
.quiz-form {
  margin-bottom: 16px;
}

/* 题目区域样式 */
.question-section {
  border-top: 1px dashed #EBEEF5;
  padding-top: 16px;
}
.question-label {
  font-size: 12px;
  color: #4E5969;
  margin-right: 12px;
}
.question-buttons {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
}
.question-table {
  background-color: #F9FAFB;
}
.question-content {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
}

/* 查看模态框样式 */
.view-course-container {
  padding: 10px 0;
}
.view-base-info {
  margin-bottom: 24px;
}
.course-name {
  font-size: 18px;
  font-weight: bold;
  color: #304156;
  margin-bottom: 8px;
}
.course-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
  font-size: 13px;
  color: #86909C;
}
.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
}
.status-tag {
  margin-left: 8px;
}

/* 查看区域标题 */
.view-section-title {
  font-size: 15px;
  font-weight: 500;
  color: #304156;
  margin-bottom: 12px;
  padding-left: 8px;
  border-left: 2px solid #165DFF;
}

/* 描述内容样式 */
.description-content {
  background-color: #F9FAFB;
  padding: 16px;
  border-radius: 4px;
  font-size: 14px;
  color: #4E5969;
  line-height: 1.6;
}

/* 测验卡片样式 */
.quiz-card {
  background-color: #FFFFFF;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  padding: 16px;
  margin-bottom: 12px;
}
.quiz-meta {
  font-size: 12px;
  color: #86909C;
}

/* 删除确认弹窗 */
.delete-content {
  text-align: center;
  padding: 24px 0;
}
.warning-icon {
  font-size: 32px;
  color: #FF7D00;
  margin-bottom: 16px;
}
.delete-message {
  font-size: 14px;
  color: #304156;
  margin-bottom: 8px;
}
.delete-tip {
  font-size: 12px;
  color: #86909C;
}

/* 模态框底部按钮区 */
.modal-footer {
  padding: 12px 20px;
  border-top: 1px solid #F2F3F5;
}

/* 课程详情查看 - 新样式 */
.view-course-container {
  max-height: 70vh;
  overflow-y: auto;
  padding: 0 10px;
}

.course-name-title {
  font-size: 24px;
  font-weight: 600;
  color: #1D2129;
  margin: 0 0 16px 0;
  text-align: left;
}

.course-meta-info {
  background: #F7F8FA;
  padding: 16px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.meta-row {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.meta-item-detail {
  display: flex;
  align-items: center;
  gap: 8px;
}

.meta-label {
  color: #86909C;
  font-size: 14px;
}

.meta-value {
  color: #1D2129;
  font-size: 14px;
  font-weight: 500;
}

.view-section {
  margin-bottom: 24px;
}

.section-title-view {
  font-size: 16px;
  font-weight: 600;
  color: #1D2129;
  margin: 0 0 12px 0;
  padding-bottom: 8px;
  border-bottom: 2px solid #E5E6EB;
  display: flex;
  align-items: center;
  gap: 8px;
  text-align: left;
}

.section-title-view i {
  color: #165DFF;
}

.section-content-view {
  padding: 12px 0;
}

.description-text {
  color: #4E5969;
  font-size: 14px;
  line-height: 1.6;
  text-align: left;
  margin: 0;
}

.quiz-detail-card {
  background: #F7F8FA;
  border-radius: 4px;
  padding: 16px;
  margin-bottom: 16px;
}

.quiz-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.quiz-card-title {
  font-size: 15px;
  font-weight: 600;
  color: #1D2129;
  margin: 0;
  text-align: left;
}

.quiz-card-meta {
  color: #86909C;
  font-size: 13px;
}

.question-text {
  text-align: left;
  line-height: 1.5;
}

.empty-tip {
  text-align: center;
  color: #86909C;
  padding: 40px 0;
  font-size: 14px;
}

/* 实训参数显示样式 */
.param-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  padding: 8px 0;
}

.param-label {
  color: #4E5969;
  font-size: 13px;
  white-space: nowrap;
  min-width: 100px;
  text-align: left;
}

.param-value {
  color: #1D2129;
  font-size: 13px;
  font-weight: 500;
  flex: 1;
  text-align: left;
}

/* 绑定学生对话框样式 */
.bind-student-container {
  padding: 0;
}

.bind-search {
  margin-bottom: 16px;
}
</style>